var delID;
var deleteFlag;
var roleInfos = [];
var roleMsgName = "";
var map = new Map();
var parentNameData = new Array();

$(document).ready(function() {
	showLoading();
	$('title', parent.document).html($('title').text());
	setBaseUrl();
	search();
});
function search(){
	$ajax('searchRole', 'searchRoleInfo', searchRoleInfo);
}
function searchRoleInfo(data) {
	roleInfos = data && data.roleInfoList || [];
	var length = roleInfos.length;
	$(".userLeftUl").html('');
	var userLeftUl = $(".userLeftUl");
	var ul = '';
	for (var i=0; i<length; i++) {
		var enabledMsg = "";
		if (roleInfos[i].enabled) {
			enabledMsg = "正在查看";
		} else {
			enabledMsg = "未选择";
		}
		ul += '<li class="userLeftClick leftClick" id="'+ roleInfos[i].roleID +'">'+ roleInfos[i].roleName +'<span class="fontValue">'
		+ '<img id="userSelectRight" class="userSelectRight" src="../static/images/userSelectRight.png" width="12" height="12"/>'
		+ '<img id="userSelectBottom" class="userSelectBottom" src="../static/images/userSelectBottom.png" width="12" height="12" hidden="hidden"/>' 
		+ '</span></li>'
		+ '<li class="showOrHide userLeftClick" hidden="hidden">' 
		+ '<ul class="userLeftUl" id="BranchCompany">'
		+ '<li style="font-size: 10px; color: #666;">&nbsp;&nbsp;&nbsp;&nbsp;级别:<span style="font-size: 10px; color: #666;">'+ roleInfos[i].level 
		+'</span>&nbsp;&nbsp;&nbsp;&nbsp;<span style="font-size: 10px; color: #666;">'+ enabledMsg +'</span></li>'
		+ '<li><a onclick="chkBefore('+ i +',\'update\')"><img src="../static/images/detalisUpdate.png" style="margin: 0px 5px;" height="12" width="12"/>编辑</a> '
		+ '<a onclick="chkBefore('+ i +',\'delete\')"><img src="../static/images/detalisDelete.png" style="margin: 0px 5px;" height="12" width="12"/>删除</a> '
        + '</li></ul></li>';
	}
	userLeftUl.append(ul);
	$(".leftClick").each(function(){
		 $(this).click(function(){
			 $("#roleID").val($(this)[0].id);
			 if ($("#RoleName").val() != $(this)[0].innerText) {
				 $(".showOrHide").hide();
				 $('.leftClick').find('img#userSelectRight').show();
		    	 $('.leftClick').find('img#userSelectBottom').hide();
			 }
			 $(this).next().toggle();
			 $(this).find('img#userSelectRight').toggle();
		     $(this).find('img#userSelectBottom').toggle();
		     $("#RoleName").val($(this)[0].innerText);
		 	 if (roleMsgName != $("#roleID").val()) {
		 		searchResource();
		 	 }
		 	 roleMsgName = $("#roleID").val();
		 });
	});
	$(function(){
		$("#name").autocomplete({
			source: parentNameData,
			minLength: 0
		});
	});
	var length = roleInfos.length;
	for (var i = 0; i < length; i++) {
		parentNameData[i] = roleInfos[i].roleName;
	}
	setTimeout(hideLoading, 500);
}
function nameValue() {
	var roleName = $("#name").val();
	$("#RoleName").val(roleName);
	search();
}
function chkBefore(index, chkFlag){
	if (chkFlag == "update") {
		update(index);
	} else if(chkFlag == "delete") {
		deleteFlag = "delete";
		delID = roleInfos[index].roleID;
		showMessge(messageContent["Delete.Confirm"], "model2");
	}
}
function save(){
	$('#saveTitle').html('');
	var saveTitle = $('#saveTitle');
	var strong = document.createElement("strong");
	strong.innerHTML = titleContent["roleInfoSave"];
	saveTitle.append(strong);
	$("#saveRoleID").attr("readonly",false);
	formReset("saveForm");
	deleteFlag = "save";
	$("#save").modal("show");
}
function update(index) {
		$('#saveTitle').html('');
		var saveTitle = $('#saveTitle');
		var strong = document.createElement("strong");
		strong.innerHTML = titleContent["roleInfoUpdate"];
		saveTitle.append(strong);
		$("#saveRoleID").val(roleInfos[index].roleID).attr("readonly",true);
		$("#saveRoleName").val(roleInfos[index].roleName);
		$("#saveLevel").val(roleInfos[index].level);
		var enabled = roleInfos[index].enabled;
		if (enabled){
			$("#saveEnabled").val(1);
		} else {
			$("#saveEnabled").val(0);
		}
		$('#save').modal('show');
	deleteFlag = "update";
}
function confirm(){
	return checkForm("saveForm", roleInfoTable);
}
function getUrl(){
	if(deleteFlag == "save"){
		return 'saveRole';
	} else if(deleteFlag == "update"){
		return 'updateRole';
	} else if(deleteFlag == "delete"){
		return 'deleteRole';
	}
}
function saveRole(data){
	if(deleteFlag == "save"){
		$('#save').modal('hide');
		formReset("saveForm");
		var result = data && data.result;
		if (result == "Success") {
			showMessge(messageContent["Insert.Success"]);
		} else if (result == "NotFound") {
			showMessge(messageContent["Insert.Failed"]);
		} else if (result == "BatteryTypeNoNull") {
			showMessge(messageContent["Battery.BatteryTypeNoNull"]);
		} else if (result == "BatteryNameNoNull") {
			showMessge(messageContent["Battery.BatteryNameNoNull"]);
		} else {
			showMessge(messageContent["Insert.Error"]);
		}
	} else if(deleteFlag == "update"){
		$('#save').modal('hide');
		formReset("saveForm");
		var result = data && data.result;
		if (result == "Success") {
			showMessge(messageContent["Update.Success"]);
		} else if (result == "NotFound") {
			showMessge(messageContent["Update.Failed"]);
		} else if (result == "BatteryNameNoNull") {
			showMessge(messageContent["Battery.BatteryNameNoNull"]);
		} else {
			showMessge(messageContent["Update.Error"]);
		}
	}
	$("#RoleName").val("");
	$("#roleID").val("");
	search();
}
function getData(){
	return {roleID: delID};
}
function sure(data){
	var result = data && data.result;
	if (result == "Success") {
		showMessge(messageContent["Delete.Success"]);
	} else if (result == "NotFound") {
		showMessge(messageContent["Delete.NotFound"]);
	} else {
		showMessge(messageContent["Delete.Error"]);
	}
	$("#RoleName").val("");
	$("#roleID").val("");
	search();
	$("#treeMenu").html('<p style="font-size: 2em;text-align: center;">请选择左侧角色查看权限！</p>');
}
/*以下为权限代码*/
function searchResource(){
	showLoading();
	$("#saveResource").hide();
	if (!map.get($("#roleID").val())) {
		$ajaxCommon('searchRoleResource', searchRoleResource, {RoleID: $("#roleID").val()});
	} else {
		searchRoleResource();
	}
}

function searchRoleResource(data){
	if (data && data.roleResourceList && data.roleResourceList.length > 0) {
		var roleNameElement = $("#RoleName").val();
		var ul = "<ul><li style='background-color:#ECECEC'><span style='color: #09be09;'>权限名称列表(" + (roleNameElement || '角色名称异常') + ")</span> " 
					+ "<a style='float: right;margin-right: 10px;' class='detalis' onclick='showAllLi()'>展开全部</a> "
					+ "<a style='float: right;margin-right: 10px;' class='detalis' onclick='hideAllLi()'>隐藏全部</a>"
					+ "</li>"
					+ "</ul>";
		ul += createTree(roleResourceBody(data.roleResourceList), 0);
		$("#treeMenu").html('');
	    $("#treeMenu").append(ul);
	    //控制菜单的隐藏显示
	    $("ul[class] li span[class]").each(function(){
		    $(this).click(function(){
		    	$(this).find('img#userSelectRight').toggle();
		    	$(this).find('img#userSelectBottom').toggle();
		    	$(this).parent().next().children("li").toggle();
		    }) ;
	    }) ;
	    map.set($("#roleID").val(), ul);
	    $("#saveResource").show();
	} else {
		if (map.get($("#roleID").val())) {
			$("#treeMenu").html('');
		    $("#treeMenu").append(map.get($("#roleID").val()));
		    $("ul[class] li span[class]").each(function(){
			    $(this).click(function(){
			    	$(this).find('img#userSelectRight').toggle();
			    	$(this).find('img#userSelectBottom').toggle();
			    	$(this).parent().next().children("li").toggle();
			    }) ;
		    }) ;
		    $("#saveResource").show();
		} else {
			$("#treeMenu").html('<p style="font-size: 2em;text-align: center;">角色权限数据不存在！</p>')
		}
	}
    setTimeout(hideLoading, 500);
}

function roleResourceBody(data,zNodes){
	var treeNodes =[];
	var dateLength = eval(data).length;
	if (dateLength == 0) {
	  showMessge(messageContent["Search.NoResultFound"]);
    } else {
    	for(var j=0; j<dateLength; j++){
		  treeNodes.push({
			"id" : eval(data)[j].resourcesID,
			"pid" : eval(data)[j].parentID,
			"name" : eval(data)[j].resourcesName + (eval(data)[j].roleName ? '' : "(没有权限)"),
			"checked" : eval(data)[j].roleID == "NotFound" ? "" : "checked" ,
	//		"click" : "child("+searchResourceData[j].resourcesID+",this)"
		});
		  }
	}
	return treeNodes;
}
//主方法，运用递归实现
function createTree(jsons, pid){
    if(jsons != null){
        var ul = "<ul class=''>" ;
        for(var i=0;i<jsons.length;i++){
            if(jsons[i].pid == pid){
            	var flag = false;
            	for(var j = 0; j < jsons.length; j++){
            		if(jsons[i].id == jsons[j].pid){
            			flag = true;
            			break;
            		}
            	}
            	if(flag){
            		if (jsons[i].pid == 0) {
                		ul += '<li><input name="chk" id="'+ jsons[i].id +'" type="checkbox"'+ jsons[i].checked +'><span class="clickUL">'
                			+ jsons[i].name 
                			+ " <img id='userSelectRight' src='../static/images/userSelectRight.png' width='12' height='12'/>"
                			+ " <img id='userSelectBottom' src='../static/images/userSelectBottom.png' width='12' height='12' hidden='hidden'/></span>"
                			+ "</li>" ;
                	} else {
                		ul += '<li style="display:none;"><input name="chk" id="'+ jsons[i].id +'" type="checkbox"'+ jsons[i].checked +'><span class="clickUL">' 
                			+ jsons[i].name 
                			+ " <img id='userSelectRight' src='../static/images/userSelectRight.png' width='12' height='12'/>"
                			+ " <img id='userSelectBottom' src='../static/images/userSelectBottom.png' width='12' height='12' hidden='hidden'/></span>"
                			+ "</li>" ;
                	}
            	} else {
            		if (jsons[i].pid == 0) {
                		ul += '<li><input name="chk" id="'+ jsons[i].id +'" type="checkbox"'+ jsons[i].checked +'><span class="clickUL">'
                			+ jsons[i].name 
                			+ " </span>"
                			+ "</li>" ;
                	} else {
                		ul += '<li style="display:none;"><input name="chk" id="'+ jsons[i].id +'" type="checkbox"'+ jsons[i].checked +'><span class="clickUL">' 
                			+ jsons[i].name 
                			+ " </span>"
                			+ "</li>" ;
                	}
            	}
                ul += createTree(jsons,jsons[i].id) ;
            }
        }
        ul += "</ul>" ;
    }
    return ul ;
}
function showAllLi() {
	$("#treeMenu ul[class] li span").each(function(){
    	$(this).parent().next().children("li").show();
    	$(this).find('img#userSelectRight').toggle(false);
    	$(this).find('img#userSelectBottom').toggle(true);
    }) ;
}
function hideAllLi() {
	$("#treeMenu ul[class] li span").each(function(){
    	$(this).parent().next().children("li").hide();
    	$(this).find('img#userSelectRight').toggle(true);
    	$(this).find('img#userSelectBottom').toggle(false);
	}) ;
}
function savePermissions(){
	var saveResourceID = [];
	var deleteResourceID = [];
	var nodes = document.getElementsByName('chk');
	var length = nodes.length;
	if(length == 0){
		showMessge(messageContent["Update.NotChange"]);
	}else{
		for (var i=0; i<length; i++) {
			if (nodes[i] && nodes[i].checked) {
				saveResourceID.push(nodes[i].id);
			} else {
				deleteResourceID.push(nodes[i].id);
			}
		}
		$ajax("saveRoleResources", 
			{
				RoleID: $("#roleID").val(), 
				saveResourceID: saveResourceID.toString(), 
				deleteResourceID: deleteResourceID.toString()
			}, 
			saveRoleResources
		);
	}
}

function saveRoleResources(data){
    var result = data && data.result;
    if (result == "Success") {
    	map.set($("#roleID").val(), undefined);
    	searchResource();
		showMessge(messageContent["Update.Success"]);
	} else if (result == "NotFound") {
		showMessge(messageContent["Update.NotFound"]);
	} else {
		showMessge(messageContent["Update.Error"]);
	}
}